<?php

/* ----------------------------------------------
  Caloris: Module Users

  $Id$
  $Author$

  Seznam uživatelů
  ---------------------------------------------- */

require_once("../../../index.php");
Caloris\ACL::authenticate();

define('_MODULE_ACTIVE', 'usermanager');

if ($_REQUEST["function_name"] == 'userDelete') {
    if (Caloris\ACL::authorize("users") == 1) {
        $user_actual = $_COOKIE["auser"];
        $username = $_POST["username"];

        if ($username == 'admin') {
            $msg = "Nemůžete smazat účet admin";
        } else {
            // Checks against deleting logged user's account
            if (strcmp($user_actual, $username) == 0) {
                $msg = "Nemůžete smazat vlastní účet";
            } else {
                // Deletes the account
                $doc = new \DOMDOcument;
                $doc->load(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');

                $xpath = new \DOMXpath($doc);
                $qry = '//user[@id="' . $username . '"]';

                foreach ($xpath->query($qry) as $node) {
                    $node->parentNode->removeChild($node);
                }

                $doc->save(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
                $msg = "Účet smazán";
            }
        }

        if ($_POST["j"] != 1) {
            header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php");
            exit();
        } else {
            echo "{\"msg\": \"" . $msg . "\"}";
            exit();
        }
    } else {
        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php.php?msg=" . urlencode("Nemáte oprávnění"));
        exit();
    }
} elseif ($_REQUEST["function_name"] == 'userCreate') {
    if (Caloris\ACL::authorize("users") == 1) {
        $username = $_POST["username"];
        $email = $_POST["email"];
        $attributes = $_POST["attributes"];
        $sendmail = $_POST["sendmail"];

//Generates password from e-mail
        $username = \Nette\Utils\Strings::webalize($username);

        $xmlUsers = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
        $userExists = $xmlUsers->xpath('//user[@id="' . $username . '"]');

        if (count($userExists) > 0) {
            header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Uživatelské jméno již existuje"));
            exit();
        }

        // Checks the validity of e-mail
        if (\Nette\Utils\Validators::isEmail($email) == false) {
            header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Nesprávný formát e-mailu"));
            exit();
        }

        $emailExists = $xmlUsers->xpath('//user[email="' . $email . '"]');

        if (count($emailExists) > 0) {
            header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Uživatelské jméno již existuje"));
            exit();
        }

        // Creates tag in pages.xml
        $doc = new \DOMDOcument;
        $doc->load(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
        $xpath = new \DOMXpath($doc);

        // Generates password
        $pwd = \Nette\Utils\Strings::random(1, 'bcdfghjklmnpqrstvwxz') . \Nette\Utils\Strings::random(1, 'aeiouy') . \Nette\Utils\Strings::random(1, 'bcdfghjklmnpqrstvwxz') . \Nette\Utils\Strings::random(1, 'aeiouy') . \Nette\Utils\Strings::random(1, 'bcdfghjklmnpqrstvwxz') . \Nette\Utils\Strings::random(1, 'aeiouy') . \Nette\Utils\Strings::random(1, 'bcdfghjklmnpqrstvwxz') . \Nette\Utils\Strings::random(1, 'aeiouy');
        $pwdenc = \Caloris\ACL::passHash($pwd);

        $qry = '/core';

        foreach ($xpath->query($qry) as $node) {
            $addElement = $doc->createElement('user');
            $node->appendChild($addElement);

            $idAttribute = $doc->createAttribute("id");
            $addElement->appendChild($idAttribute);

            $idAttributeAdmin = $doc->createAttribute("admin");
            $addElement->appendChild($idAttributeAdmin);

            $p1 = $doc->createTextNode($username);
            $idAttribute->appendChild($p1);

            $p2 = $doc->createTextNode(1);
            $idAttributeAdmin->appendChild($p2);

            $p3 = $doc->createElement("password", $pwdenc);
            $addElement->appendChild($p3);

            $p4 = $doc->createElement("email", $email);
            $addElement->appendChild($p4);

            $p5 = $doc->createElement("date");
            $addElement->appendChild($p5);

            $p6 = $doc->createElement("created", date("Y-m-d H:i:s"));
            $p5->appendChild($p6);

            $p7 = $doc->createElement("state");
            $addElement->appendChild($p7);

            $p8 = $doc->createElement("permissions", $attributes);
            $p7->appendChild($p8);
        }

        $doc->save(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');

        if (class_exists('tidy')) {
            $tidy_options = array(
                'input-xml' => true,
                'output-xml' => true,
                'indent' => true,
                'wrap' => false,
                'indent-cdata' => true,
            );

            $tidy = new \tidy();
            $tidy->parseFile(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml', $tidy_options, 'utf8');
            $tidy->cleanRepair();

            $xmm = simplexml_load_string($tidy);
            $xmm->asXML(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
        }

// Sending e-mail with information for users

        if ($sendmail == 1) {
            $message = "
Vítejte v administraci stránek " . _CALSET_BASIC_TITLE . "<br />
<br />
Do administrace se můžete přihlásit na této adrese: <a href=\"" . _CALSET_PATHS_URI . "/administrator\">" . _CALSET_PATHS_URI . "/administrator</a> s následujícím uživatelským jménem a heslem<br />
<br />
Uživatelské jméno: $username<br />
Heslo: $pwd<br />
<br />
Pokud máte jakékoliv otázky, neváhejte nám je poslat na tento e-mail: <a href=\"mailto:" . _CALSET_BASIC_ADMIN_EMAIL . "\">" . _CALSET_BASIC_ADMIN_EMAIL . "</a>";

// Determine the identifier for details file
            $xmlUsersCheck = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
            $userExists = $xmlUsersCheck->xpath('//user[@id="' . $username . '"]');

            if (count($userExists) == 0) {
                header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Účet nebyl vytvořen."));
                exit();
            }

            $mail = new \Nette\Mail\Message;
            $mail->setFrom('Caloris System <' . _CALSET_BASIC_ADMIN_EMAIL . '>')
                    ->addTo($email)
                    ->setSubject(_CALSET_BASIC_TITLE . ": Informace o účtu")
                    ->setHTMLBody($message)
                    ->send();

            header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/users.detail.php?idf=$username&msg=" . urlencode("$username přidán"));
            exit();
        } else {
            $xmlUsersCheck = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
            $userExists = $xmlUsersCheck->xpath('//user[@id="' . $username . '"]');

            if (count($userExists) == 0) {
                header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Účet nebyl vytvořen."));
                exit();
            } else {
                $genmsg = "Heslo uživatele je $pwd";
                header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/users.detail.php?idf=$id&msg=" . urlencode($genmsg));
                exit();
            }
        }
    } else {
        header("location: " . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . "/" . _MODULE_ACTIVE . "/index.php?msg=" . urlencode("Nemáte oprávnění"));
        exit();
    }
}

$content = '<h1>Uživatelé</h1>';

$content .= '
<h1>Nový uživatel</h1>

<p class="perex">Uživateli bude zaslán e-mail s nově vygenerovaným heslem.</p>

<form action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/' . _MODULE_ACTIVE . '/index.php" method="post" class="form-horizontal">
<input type="hidden" name="action" value="userCreate"  />
<div class="control-group">
<label class="control-label" for="inputUser">Uživatelské jméno</label>
<div class="controls">
<input type="text" name="username" />
</div>
  </div>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="text" name="email" id="inputEmail" placeholder="Email">
</div>
</div>
<div class="control-group">
    <label class="control-label" for="inputAttributes">Práva</label>
    <div class="controls">
    <select name="attributes">';

$xmlPermissionsF = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/permissions.xml');
$xmlPermissions = $xmlPermissionsF->xpath('//permission');

// sort by name
function sort_trees($t1, $t2) {
    return strcoll($t1->name, $t2->name);
}

usort($xmlPermissions, 'sort_trees');

if (count($xmlPermissions) > 0) {
    for ($a = 0; $a < count($xmlPermissions); $a++) {
        $content .= '   <option value="' . $xmlPermissions[$a]["id"] . '">' . $xmlPermissions[$a]->name . '</option>' . PHP_EOL;
    }
}

$content .= '
    </select>
    </div>
</div>
<div class="control-group">
        <label class="control-label" for="inputSendEmail">Poslat e-mail</label>
    <div class="controls">
        <input type="checkbox" value="1" />
    </div>
</div>
<div class="control-group">
    <div class="controls"><button type="submit" class="btn">Sign in</button></div>
</div>
</form>' . PHP_EOL;

// Listování uživatelů

$content .= '
<h2>Seznam uživatelů</h2>';

$xmlPermission = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/permissions.xml');

$xmlUsersF = simplexml_load_file(_CALSET_PATHS_BASE . _CALSET_DIRS_DATA . '/users.xml');
$xmlUsers = $xmlUsersF->xpath('//user');

usort($xmlUsers, 'sort_trees');

if (count($xmlUsers) > 0) {
    $content .= '
<table class="table table-striped">
    <tr>
        <th style="width: 20px;">&nbsp;</th>
        <th style="width: 150px;">Uživatel</th>
        <th style="width: 70px;">Typ</th>
        <th style="width: 70px;">Oprávnění</th>
        <th>E-mail</th>
    </tr>' . PHP_EOL;

    for ($a = 0; $a < count($xmlUsers); $a++) {
        $resultPermission = $xmlPermission->xpath('//permission[@id="' . $xmlUsers[$a]->state->permissions . '"]');
        $attributetext = $resultPermission[0]->name;

        if ($xmlUsers[$a]["admin"] == 1) {
            $typeUser = 'Uživatel';
        } else {
            $typeUser = 'Člen';
        }

        if (Caloris\ACL::authorize("users") == 1 && $xmlUsers[$a]->system != 1) {
            $delete = '
<form id="formshw_' . $a . '" action="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/' . _MODULE_ACTIVE . '/index.php" name="trbl_' . $a . '" method="post" onsubmit="return false;">
<input type="hidden" name="function_name" value="userDelete"  />
<input type="hidden" name="username" value="' . $xmlUsers[$a]["id"] . '"  />
<input type="submit" id="formx_' . $a . '" value="Smazat" class="btn btn-danger" />
</form>';
        } else {
            $delete = '';
        }

        $content .= '
    <tr id="trbl_' . $a . '" >
        <td>' . $delete . '</td>
        <td><a href="' . _CALSET_PATHS_URI . _CALSET_DIRS_MODULE . '/' . _MODULE_ACTIVE . '/users.detail.php?idf=' . $xmlUsers[$a]["id"] . '">' . $xmlUsers[$a]["id"] . '</a></td>
        <td>' . $typeUser . '</td>
        <td>' . $attributetext . '</td>
        <td>' . $xmlUsers[$a]->email . '</td>
    </tr>' . PHP_EOL;

        unset($delete);
    }


    $content .= '</table>' . PHP_EOL;
} else {
    $content .= '<p>Žádní uživatelé nenalezeni</p>';
}

$data["title"] = 'Uživatelé';

$tmpl = new Caloris\Template;
$tmpl->input($content);
$tmpl->renderHead($data);
echo $tmpl->renderBody('caloris-admin');